//部分函数
var net = require('../../utils/ajax.js');
var url = require('../../utils/url.js');
var func = require('../../utils/func.js');
var conf = require('../../utils/config.js');
var user = require('../../utils/user.js');
var Promise = require('../../libs/promise.js');

var event = require('../../utils/eventManager.js');

var me;
var uploadImgListKeys = [];
var isUploading = false;
var draftId;
var uid;
var publishSucceed = false;

let loadDraft = () => {
    if (!!draftId) {
        return net.send(url.getDraft, {
            id: draftId
        }).then(res => {
            transformContent(res);
        })
    } else {
        return new Promise((resolve, reject) => {
            resolve();
        })
    }
}

let transformContent = (res) => {
    let content = res.info;
    let list = content.list;
    let contentParse = [];

    if (!list) {
        me.setData({
            title: res.info.title,
            id: res.info.id
        })
        return;
    }

    for (let i = 0; i < list.length; i++) {
        let obj = {};
        if (list[i].type == "标题") {
            obj = {
                index: i,
                type: "title",
                typename: "标题",
                text: list[i].text,
                id: "title_" + i.toString()
            }
        } else if (list[i].type == "文本") {
            obj = {
                index: i,
                type: "text",
                typename: "文本",
                text: list[i].text,
                id: "text_" + i.toString()
            }
        } else if (list[i].type == "图片") {
            obj = {
                index: i,
                type: "image",
                typename: "图片",
                text: list[i].text,
                removeSrc: list[i].src,
                maskText: "",
                id: "image_" + i.toString()
            }
        } else if (list[i].type == "分割线") {
            obj = {
                index: i,
                type: "line",
                typename: "分割线",
                id: "line_" + i.toString()
            }
        }
        contentParse.push(obj);
    }

    me.setData({
        title: res.info.title,
        id: res.info.id,
        content: contentParse
    })

    saveDrafts();
};

let openAction = function (content, index) {
    wx.showActionSheet({
        itemList: ["分割线", "引用"],
        success: (res) => {
            if (res.tapIndex == 0) {
                let now = new Date().getTime().toString();
                let obj = {
                    type: "line",
                    index: index,
                    typename: "分割线",
                    id: ("line" + now),
                    text: ""
                }

                content.push(obj);

                me.setData({
                    content: content
                });

                saveDrafts();
            }
        }
    });
};

let saveDrafts = function () {
    let draft = {};
    isSave = false;

    let info = me.data;

    if (!!info.title && info.title.length == 0 && info.content.length == 0) {
        return;
    }

    if (isUploading) {
        return;
    }

    let article = {
        id: info.id,
        title: info.title,
        time: info.time,
        userInfo: info.userInfo,
        content: info.content
    }

    draft = article;

    if (!!draftId) {
        func.setStorge("draft_" + draftId.toString(), draft).then((res) => {
            console.log(res);
        }).catch((error) => {
            console.log(error);
        })
    } else {
        func.setStorge("draft_temp_" + uid.toString(), draft).then((res) => {
            console.log(res);
        }).catch((error) => {
            console.log(error);
        })
    }

};

let prepareUploadData = () => {
    return new Promise((resolve, reject) => {
        let data = me.data;
        let content = data.content;
        let list = [];
        for (let i = 0; i < content.length; i++) {
            let obj = {}
            if (content[i].type == "text") {
                obj = {
                    type: "文本",
                    text: content[i].text
                }
                list.push(obj);
            } else if (content[i].type == "image") {
                obj = {
                    type: "图片",
                    text: content[i].text,
                    src: content[i].removeSrc
                }
                list.push(obj);
            } else if (content[i].type == "title") {
                obj = {
                    type: "标题",
                    text: content[i].text
                }
                list.push(obj);
            } else if (content[i].type == "line") {
                obj = {
                    type: "分割线"
                }
                list.push(obj);
            }
        }

        let params = {
            uid: uid,
            title: data.title,
            id: ""
        }

        params.list = JSON.stringify(list);


        console.log(params);
        resolve(params);
    })

}

let type;
let aid;
let app = getApp();
let isSave = false;

Page({
    data: {
        id: "",
        title: "",
        time: "",
        userInfo: "",
        log: "",
        contentImageHeight: "",
        //文档内容包含类型有 title,text,image,line
        content: [],
        loadReady: false,
        toolBarActive: false,
        toolBarActiveIndex: "",
        bannerMaskShow: false,
        bannerMaskText: "正在上传"
    },
    onLoad(e) {
        me = this;
        uid = user.userInfo.uid;

        console.log(e);

        event.listenEvent("editor", ({index, data}) => {
            this.changeText(index, data);
        })

        if (e.type == "reEdit") {
            type = "reEdit";
            aid = e.aid;
        } else {
            this.setData({
                id: e.id
            });
            draftId = e.id;
            func.loading(loadDraft(), this);
        }
    },
    onReady() {
        //获取时间和用户名称
        let time = new Date();
        let now = new Date().getTime().toString();

        this.setData({
            time: (time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()),
            userInfo: user.userInfo
        });
    },
    changeText(index, data) {
        var content = this.data.content;
        content[index].text = data.text;
        this.setData({
            content: content
        })
    },
    addbanner() {
        var chooseImg = func.chooseImg(1);

        chooseImg.then((res) => {
            let paths = res.tempFilePaths;
            let now = new Date().getTime().toString();

            console.log(paths);

            isUploading = true;
            func.getToken(paths, (res) => {
                isUploading = false;
                uploadImgListKeys = res;
                saveDrafts();
            }, (status, index, key) => {
                if (status) {
                    console.log("第" + index + "个上传成功");
                    this.setData({
                        banner: conf.imgBaseUrl + key,
                        bannerMaskText: "上传成功",
                    })

                    setTimeout(() => {
                        this.setData({
                            bannerMaskShow: false
                        })
                    }, 1000)
                } else {
                    console.log("第" + index + "个上传失败");
                }
            }, () => {
                this.setData({
                    banner: paths[0],
                    bannerMaskShow: true
                })
                console.log(this);
            });
        }).catch((error) => {
            isUploading = false;
            console.log(error);
        })
    },
    toInsert(e) {
        var info = e.target.dataset;
        var index = info.index;
        var content = this.data.content;
        var toolBarActiveIndex = this.data.toolBarActiveIndex;

        if (toolBarActiveIndex != "" || toolBarActiveIndex === 0) {
            content[toolBarActiveIndex].toolBarActive = false;
        }

        if (index == "end") {
            this.setData({
                toolBarActive: true,
                toolBarActiveIndex: "",
                content: content
            })
        } else {
            content[index].toolBarActive = true;
            this.setData({
                content: content,
                toolBarActive: false,
                toolBarActiveIndex: index
            })
        }
    },
    toEditor(e) {
        var index = e.target.dataset.index;
        func.navigateTo("../editor/editor?index=" + index);
    },
    changePos(e) {
        if (isUploading) {
            return;
        }

        let info = e.target.dataset;
        let index = info.index;
        let content = this.data.content;
        let cell = content[index];
        //up
        if (info.taptype == 2) {
            content[index] = content[index - 1];
            content[index - 1] = cell;
            content[index].index = index;
            content[index - 1].index = parseInt(index - 1);
            this.setData({
                content: content
            })
        }
        //down
        if (info.taptype == 1) {
            let downnum = parseInt(index) + 1;
            content[index] = content[downnum];
            content[downnum] = cell;
            content[index].index = index;
            content[downnum].index = downnum;
            this.setData({
                content: content
            })
        }
        saveDrafts();
    },
    deletePos(e) {
        if (isUploading) {
            return;
        }

        let info = e.target.dataset;
        let index = info.index;
        let content = this.data.content;
        content.splice(index, 1);
        for (let i = 0; i < content.length; i++) {
            content[i].index = i;
        }
        this.setData({
            content: content
        })
        saveDrafts();
    },
    addContent(e) {
        let info = e.currentTarget.dataset;
        let addtype = info.addtype;
        let content = this.data.content;

        let index = info.index;

        if (index == "end") {
            index = this.data.content.length;
        }

        if (addtype == "others") {
            openAction(content, index);
            return;
        }

        if (addtype == "image") {
            let chooseImg = func.chooseImg();
            chooseImg.then((res) => {
                let paths = res.tempFilePaths;
                let now = new Date().getTime().toString();
                isUploading = true;
                func.getToken(paths, (res) => {
                    isUploading = false;
                    uploadImgListKeys = res;
                    saveDrafts();
                }, (status, index, key) => {
                    if (status) {
                        console.log("第" + index + "个上传成功");
                        let imgs = this.data.content;
                        for (let i = 0; i < imgs.length; i++) {
                            if (imgs[i].id == (now + "_" + index)) {
                                imgs[i].maskText = "";
                                imgs[i].removeSrc = conf.imgBaseUrl + key;
                                if (!!imgs[i + 1] && (imgs[i + 1].id == (now + "_" + (parseInt(index) + 1).toString()))) {
                                    imgs[i + 1].maskText = "正在上传";
                                }
                                this.setData({
                                    content: imgs
                                })
                                break;
                            }
                        }
                    } else {
                        console.log("第" + index + "个上传失败");
                    }
                }, () => {
                    for (let i = 0; i < paths.length; i++) {
                        let obj = {
                            type: "image",
                            index: (parseInt(index) + parseInt(i)),
                            typename: "图片",
                            src: paths[i],
                            maskText: ((i == 0) ? "正在上传" : "等待上传"),
                            id: (now + "_" + i),
                            text: "",
                            removeSrc: ""
                        }
                        content.splice((parseInt(index) + parseInt(i)), 0, obj);
                        //content.push(obj);
                    }
                    for (let i = 0; i < content.length; i++) {
                        content[i].index = i;
                        if (content[i].toolBarActive) {
                            content[i].toolBarActive = false;
                        }
                    }

                    this.setData({
                        content: content,
                        toolBarActive: false,
                        toolBarActiveIndex: ""
                    })
                    console.log(this);
                });
            }).catch((error) => {
                isUploading = false;
                console.log(error);
            })
        } else {
            let now = new Date().getTime().toString();
            let obj = {
                type: addtype,
                index: index,
                typename: info.typename,
                id: (addtype + now),
                text: ""
            }
            content.splice((parseInt(index)), 0, obj);
            //content.push(obj);

            for (let i = 0; i < content.length; i++) {
                content[i].index = i;
                if (content[i].toolBarActive) {
                    content[i].toolBarActive = false;
                }
            }

            this.setData({
                content: content,
                toolBarActive: false,
                toolBarActiveIndex: ""
            });

            saveDrafts();
        }
    },
    titlechange(e) {
        this.setData({
            title: e.detail.value
        })
        if (e.detail.value != '') {
            saveDrafts();
        }
    },
    previewArticle() {
        let id = this.data.id;
        wx.navigateTo({
            url: '../previewArticle/previewArticle?id=' + id,
            success: function (res) {
                wx.setNavigationBarTitle({
                    title: '预览'
                })
            }
        })
    },
    publish() {
        let data = prepareUploadData();
        data.then(res => {
            if (!!aid) {
                res.part_id = aid;
            }
            res.id = draftId;
            net.send(url.publishArticle, res).then(e => {
                console.log(e);
                if (e.status == "y") {
                    func.showToast("发布成功!");
                    publishSucceed = true;
                    deleteDraft();
                    wx.navigateBack({
                        delta: 1
                    })
                } else {
                    func.showToast("发布失败!", "loading");
                }
            })
        })
    },
    save() {
        let data = prepareUploadData();
        data.then(res => {
            res.id = draftId;
            net.send(url.saveDraft, res).then(e => {
                console.log(e);
                draftId = e.info;
                this.setData({
                    id: e.info
                })
                func.showToast("保存成功!");

                event.fireEvent("refreshMain");

                isSave = true;
            })
        })
    },
    onUnload() {
        if (this.data.title == "" || isUploading || publishSucceed || !!aid || isSave) {
            return;
        }
        func.showModal("提示", "页面已经改动,你要保存该草稿吗?").then(() => {
            this.save();
        })
    },
    previewImage(e) {
        let src = e.target.dataset.src;

        let urls = [];
        let content = this.data.content;
        for (let i = 0; i < content.length; i++) {
            if (content[i].type == "image") {
                urls.push(content[i].removeSrc);
            }
        }
        func.previewImage(src, urls);
    }
})